package org.alvin.code.tools;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 文件操作
 */
public class AFileUtils {


    public static void cp(Path src,Path dist) throws IOException {
        Files.copy(src,dist, StandardCopyOption.REPLACE_EXISTING);
    }

    public static void cp(String src,String dist) throws IOException {
        cp(Paths.get(src),Paths.get(dist));
    }

    public static void mv(String src,String dist) throws IOException {
        mv(Paths.get(src),Paths.get(dist));
    }

    public static void mv(Path src,Path dist) throws IOException {
        Files.move(src,dist,StandardCopyOption.REPLACE_EXISTING);
    }

    public static void del(Path path) throws IOException {
        Files.deleteIfExists(path);
    }

    public static void delDir(Path dir) throws IOException {
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult visitFile(Path file,
                                             BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
            // 再去遍历删除目录
            @Override
            public FileVisitResult postVisitDirectory(Path dir,
                                                      IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
        Files.deleteIfExists(dir);
    }

    public static void mergeFiles(Path dist,Path ...files) throws IOException {
      try(OutputStream out =  Files.newOutputStream(dist,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.CREATE_NEW)) {
          System.out.println("目标文件："+ dist);
          for (Path f : files) {
              System.out.println("合并的文件："+ f);
              InputStream is = Files.newInputStream(f);
              byte [] buff = new byte[2048];
              int len  ;
              while((len = is.read(buff)) != -1){
                  out.write(buff,0,len);
                  out.flush();
              }
              out.write(System.lineSeparator().getBytes());
          }
      }
    }


}
